package com.yzcrm.erp.admin.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.core.paragetter.Para;
import com.jfinal.plugin.activerecord.Record;
import com.yzcrm.common.annotation.NotNullValidate;
import com.yzcrm.common.annotation.Permissions;
import com.yzcrm.erp.admin.entity.AdminField;
import com.yzcrm.erp.admin.entity.AdminFieldSort;
import com.yzcrm.erp.admin.entity.AdminFieldStyle;
import com.yzcrm.erp.admin.service.AdminFieldService;
import com.yzcrm.erp.crm.common.CrmEnum;
import com.yzcrm.erp.crm.service.*;
import com.yzcrm.erp.finance.service.FinancePurchaseService;
import com.yzcrm.erp.finance.service.FinanceSupplierService;
import com.yzcrm.erp.kms.service.KmsBbsService;
import com.yzcrm.erp.kms.service.KmsCourseService;
import com.yzcrm.erp.kms.service.KmsFileService;
import com.yzcrm.erp.kms.service.KmsResourceService;
import com.yzcrm.erp.oa.service.OaExamineCategoryService;
import com.yzcrm.erp.psi.service.PsiEnterLeaveStockService;
import com.yzcrm.erp.psi.service.PsiStoreHouseService;
import com.yzcrm.erp.crm.service.CrmQuotationCombinationService;
import com.yzcrm.swagger.annotation.ActionApi;
import com.yzcrm.swagger.annotation.Api;
import com.yzcrm.swagger.annotation.Param;
import com.yzcrm.swagger.annotation.Params;
import com.yzcrm.utils.AuthUtil;
import com.yzcrm.utils.R;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author hmb
 */
@Api(remark = "共通：自定义字段")
public class AdminFieldController extends Controller {

    @Inject
    private AdminFieldService adminFieldService;

    @Inject
    private CrmCustomerService crmCustomerService;

    @Inject
    private CrmBusinessService crmBusinessService;

    @Inject
    private CrmContactsService crmContactsService;

    @Inject
    private CrmContractService crmContractService;

    @Inject
    private CrmLeadsService crmLeadsService;

    @Inject
    private CrmProductService crmProductService;

    @Inject
    private CrmReceivablesService crmReceivablesService;

    @Inject
    private CrmReceivablesPlanService crmReceivablesPlanService;

    @Inject
    private OaExamineCategoryService oaExamineCategoryService;

    @Inject
    private CrmPreSalesService crmPreSalesService;

    @Inject
    private PsiStoreHouseService psiStoreHouseService;

    @Inject
    private FinanceSupplierService financeSupplierService;

    @Inject
    private PsiEnterLeaveStockService psiEnterLeaveStockService;

    @Inject
    private FinancePurchaseService financePurchaseService;

    @Inject
    private CrmQuotationCombinationService crmQuotationCombinationService;

    @Inject
    private KmsFileService kmsFileService;

    @Inject
    private KmsResourceService kmsResourceService;

    @Inject
    private KmsCourseService kmsCourseService;

    @Inject
    private KmsBbsService kmsBbsService;

    /**
     * @author zhangzhiwei
     * 保存自定义字段
     */
    @Permissions("manage:crm:field")
    @ActionApi(summary = "保存自定义字段", remark = "保存自定义字段")
    @Params({
            @Param(name = "label", remark = "标签", dataType = "int", defaultValue = "", required = true)
    })
    public void save() {
        String str = getRawData();
        JSONObject jsonObject = JSON.parseObject(str);
        renderJson(adminFieldService.save(jsonObject));
    }

    /**
     * @author zhangzhiwei
     * 保存自定义字段(工作台)
     */
    @Permissions("manage:oa:examine")
    public void examineFieldSave() {
        String str = getRawData();
        JSONObject jsonObject = JSON.parseObject(str);
        renderJson(adminFieldService.save(jsonObject));
    }

    /**
     * 检索客户管理自定义字段设置 label 列表
     */
    @ActionApi(summary = "根据realm检索客户管理自定义label列表",
            remark = "客户关系crm所属label：1、线索 2、客户 3、联系人 4、产品 5、商机 6、合同 7、回款 8、回款计划 11、售前管理。" +
                    "进销存psi所属label：20销售退货 21归还入库 22维修入库 23内部测试入库 24盘盈 25其它入库 30采购入库  40销售出库 41借用出库 42维修出库 43内部测试出库 44盘亏出库 45其它出库" +
                    "财务finance所属label：50采购 60供货商 ")
    @Params({
            @Param(name = "realm", remark = "模块名称值：crm, psi, finance", dataType = "String", defaultValue = "", required = true)
    })
    public void queryFields(@Para("realm") String realm) {
        renderJson(adminFieldService.queryFields(realm));
    }

    /**
     * @author zxy
     * 查询自定义字段列表
     */
    @ActionApi(summary = "检索标签下所有的自定义字段，operating：0 改删 1 改 2 删 3 无", remark = "label：1、线索 2、客户 3、联系人 4、产品 5、商机 6、合同 7、回款 8、回款计划 11、售前管理")
    @Params({
            @Param(name = "label", remark = "标签", dataType = "int", defaultValue = "", required = true),
            @Param(name = "categoryId", remark = "和examine_category_id 审批ID比较相等，label为10需要", dataType = "int", defaultValue = "", required = false)
    })
    public void list() {
        JSONObject object = JSONObject.parseObject(getRawData());
        renderJson(R.ok().put("data", adminFieldService.list(object.getInteger("label"), object.getString("categoryId"))));
    }

    /**
     * @author wyq
     * 查询新增或编辑字段
     */
    public void queryField(@Para("label") Integer label, @Para("id") Integer id) {
        List<Record> recordList = new LinkedList<>();
        CrmEnum crmEnum = CrmEnum.parse(label);
        if (id != null) {
            if (CrmEnum.CRM_LEADS.equals(crmEnum)) {
                recordList = crmLeadsService.queryField(id);
            }
            if (CrmEnum.CRM_CUSTOMER.equals(crmEnum)) {
                recordList = crmCustomerService.queryField(id);
            }
            if (CrmEnum.CRM_CONTACTS.equals(crmEnum)) {
                recordList = crmContactsService.queryField(id);
            }
            if (CrmEnum.CRM_PRODUCT.equals(crmEnum)) {
                recordList = crmProductService.queryField(id, label);
            }
            if (CrmEnum.CRM_BUSINESS.equals(crmEnum)) {
                recordList = crmBusinessService.queryField(id);
            }
            if (CrmEnum.CRM_CONTRACT.equals(crmEnum)) {
                recordList = crmContractService.queryField(id);
            }
            if (CrmEnum.CRM_RECEIVABLES.equals(crmEnum)) {
                recordList = crmReceivablesService.queryField(id);
            }
            if (CrmEnum.CRM_RECEIVABLES_PLAN.equals(crmEnum)) {
                recordList = crmReceivablesPlanService.queryField(id);
            }
            if (10 == label) {
                recordList = oaExamineCategoryService.queryField(id);
            }
            if (CrmEnum.CRM_PRE_SALES.equals(crmEnum)) {
                recordList = crmPreSalesService.queryField(id);
            }
            if (CrmEnum.PSI_STOREHOUSE.equals(crmEnum)) {
                recordList = psiStoreHouseService.queryField(id);
            }
            if (CrmEnum.PSI_PRODUCT.equals(crmEnum)) {
                recordList = crmProductService.queryField(id, label);
            }
            if (CrmEnum.FINANCE_SUPPLIER.equals(crmEnum)) {
                recordList = financeSupplierService.queryField(id);
            }
            if (CrmEnum.FINANCE_PURCHASE.equals(crmEnum)
                    || CrmEnum.FINANCE_OFFICE_PURCHASE.equals(crmEnum)
                    || CrmEnum.FINANCE_NORMAL_PURCHASE.equals(crmEnum)
                    || CrmEnum.FINANCE_PROJECT_PURCHASE.equals(crmEnum)
                    || CrmEnum.FINANCE_DEV_PURCHASE.equals(crmEnum)
                    || CrmEnum.FINANCE_OTHER_PURCHASE.equals(crmEnum)) {
                recordList = financePurchaseService.queryField(id, label);
            }
            if (CrmEnum.PSI_SALES_ENTER.equals(crmEnum)
                    || CrmEnum.PSI_RETRUN_ENTER.equals(crmEnum)
                    || CrmEnum.PSI_REPAIR_ENTER.equals(crmEnum)
                    || CrmEnum.PSI_TEST_ENTER.equals(crmEnum)
                    || CrmEnum.PSI_INVENTORY_PROFIT_ENTER.equals(crmEnum)
                    || CrmEnum.PSI_OTHER_ENTER.equals(crmEnum)
                    || CrmEnum.PSI_PURCHASE_ENTER.equals(crmEnum)
                    || CrmEnum.PSI_SALES_LEAVE.equals(crmEnum)
                    || CrmEnum.PSI_BORROW_LEAVE.equals(crmEnum)
                    || CrmEnum.PSI_REPAIR_LEAVE.equals(crmEnum)
                    || CrmEnum.PSI_TEST_LEAVE.equals(crmEnum)
                    || CrmEnum.PSI_INVENTORY_LOSS_LEAVE.equals(crmEnum)
                    || CrmEnum.PSI_OTHER_LEAVE.equals(crmEnum)) {
                recordList = psiEnterLeaveStockService.queryField(id, label);
            }
            if (CrmEnum.KMS_FILE.equals(crmEnum)){
                recordList = kmsFileService.queryField(id);
            }
            if (CrmEnum.KMS_RESOURCE.equals(crmEnum)){
                recordList = kmsResourceService.queryField(id);
            }
            if (CrmEnum.KMS_COURSE.equals(crmEnum)){
                recordList = kmsCourseService.queryField(id);
            }
            if (CrmEnum.KMS_BBS.equals(crmEnum)){
                recordList = kmsBbsService.queryField(id);
            }
            if (CrmEnum.CRM_QUOTATION_COMBINATION.equals(crmEnum)){
                recordList = crmQuotationCombinationService.queryField(id);
            }
        }else {
            if (CrmEnum.CRM_RECEIVABLES_PLAN.equals(crmEnum)){
                recordList = crmReceivablesPlanService.queryField();
            } else {
                recordList = adminFieldService.queryAddField(crmEnum);
            }
        }
        renderJson(R.ok().put("data", recordList));
    }

    /**
     * @param types 模块类型
     * @param id    查询基本信息
     * @author wyq
     */
    public void information(@Para("types") Integer types, @Para("id") Integer id) {
        List<Record> recordList;
        boolean auth;
        if (types.equals(2)) {
            auth = AuthUtil.isPoolAuth(id);
        } else {
            auth = AuthUtil.isCrmAuth(CrmEnum.parse(types), id);
        }
        if (auth) {
            renderJson(R.noAuth());
            return;
        }
        if (1 == types) {
            recordList = crmLeadsService.information(id);
        } else if (2 == types) {
            recordList = crmCustomerService.information(id);
        } else if (3 == types) {
            recordList = crmContactsService.information(id);
        } else if (4 == types) {
            recordList = crmProductService.information(id, types);
        } else if (5 == types) {
            recordList = crmBusinessService.information(id);
        } else if (6 == types) {
            recordList = crmContractService.information(id);
        } else if (7 == types) {
            recordList = crmReceivablesService.information(id);
        } else if (11 == types) {
            recordList = crmPreSalesService.information(id);
        } else if (CrmEnum.PSI_STOREHOUSE.getType() == types) {
            recordList = psiStoreHouseService.information(id);
        } else if (CrmEnum.PSI_PRODUCT.getType() == types) {
            recordList = crmProductService.information(id, types);
        } else if (CrmEnum.FINANCE_SUPPLIER.getType() == types) {
            recordList = financeSupplierService.information(id);

        } else if (CrmEnum.FINANCE_PURCHASE.getType() == types
                || CrmEnum.FINANCE_OFFICE_PURCHASE.getType() == types
                || CrmEnum.FINANCE_NORMAL_PURCHASE.getType() == types
                || CrmEnum.FINANCE_PROJECT_PURCHASE.getType() == types
                || CrmEnum.FINANCE_DEV_PURCHASE.getType() == types
                || CrmEnum.FINANCE_OTHER_PURCHASE.getType() == types) {

            recordList = financePurchaseService.information(types, id);

        } else if (CrmEnum.PSI_SALES_ENTER.getType() == types
                || CrmEnum.PSI_RETRUN_ENTER.getType() == types
                || CrmEnum.PSI_REPAIR_ENTER.getType() == types
                || CrmEnum.PSI_TEST_ENTER.getType() == types
                || CrmEnum.PSI_INVENTORY_PROFIT_ENTER.getType() == types
                || CrmEnum.PSI_OTHER_ENTER.getType() == types
                || CrmEnum.PSI_PURCHASE_ENTER.getType() == types
                || CrmEnum.PSI_SALES_LEAVE.getType() == types
                || CrmEnum.PSI_BORROW_LEAVE.getType() == types
                || CrmEnum.PSI_REPAIR_LEAVE.getType() == types
                || CrmEnum.PSI_TEST_LEAVE.getType() == types
                || CrmEnum.PSI_INVENTORY_LOSS_LEAVE.getType() == types
                || CrmEnum.PSI_OTHER_LEAVE.getType() == types) {
            recordList = psiEnterLeaveStockService.information(types, id);

        } else {
            recordList = new ArrayList<>();
        }
        renderJson(R.ok().put("data", recordList));
    }

    /**
     * @author zhangzhiwei
     * 设置字段样式
     */
    public void setFelidStyle() {
        renderJson(adminFieldService.setFelidStyle(getKv()));
    }

    /**
     * @author zhangzhiwei
     * 验证字段数据
     */
    @NotNullValidate(value = "value", message = "字段校验参数错误")
    @NotNullValidate(value = "fieldId", message = "字段校验参数错误")
    public void verify(@Para("fieldId") Integer fieldId, @Para("value") String value, @Para("batchId") String batchId) {
        AdminField adminField = AdminField.dao.findByIdLoadColumns(fieldId, "field_name,field_id,name,label,field_type");
        adminField.put("value", value).put("batchId", batchId);

        int num = adminFieldService.verify(CrmEnum.parse(adminField.getLabel()), adminField.toRecord());
        renderJson(R.isSuccess(num == 0, adminField.getName() + "已存在"));
    }

    /**
     * @author wyq
     * 查询客户管理列表页字段
     */
    @NotNullValidate(value = "label", message = "label不能为空")
    public void queryListHead(@Para("") AdminFieldSort adminFieldSort) {
        List<Record> records;
        if (adminFieldSort.getLabel() == 10) {
            records = oaExamineCategoryService.queryFieldList();
        } else {
            records = adminFieldService.queryListHead(adminFieldSort);
        }
        List<AdminFieldStyle> fieldStyles = adminFieldService.queryFieldStyle(adminFieldSort.getLabel().toString());
        records.forEach(record -> {
            for (AdminFieldStyle fieldStyle : fieldStyles) {
                if (record.get("fieldName") != null && fieldStyle.getFieldName().equals(record.get("fieldName"))) {
                    record.set("width", fieldStyle.getStyle());
                    break;
                }
            }
            if (!record.getColumns().containsKey("width")) {
                record.set("width", 130);
            }
        });
        renderJson(R.ok().put("data", records));
    }

    /**
     * @author wyq
     * 查询字段排序隐藏设置
     */
    @NotNullValidate(value = "label", message = "label不能为空")
    public void queryFieldConfig(@Para("") AdminFieldSort adminFieldSort) {
        renderJson(adminFieldService.queryFieldConfig(adminFieldSort));
    }

    /**
     * @author wyq
     * 设置字段排序隐藏
     */
    @NotNullValidate(value = "label", message = "label不能为空")
    @NotNullValidate(value = "noHideIds", message = "显示列不能为空")
    public void fieldConfig(@Para("") AdminFieldSort adminFieldSort) {
        renderJson(adminFieldService.fieldConfig(adminFieldSort));
    }

    /**
     * @author wyq
     * 获取导入查重字段
     */
    public void getCheckingField(@Para("type") Integer type) {
        R data;
        switch (type) {
            case 1:
                data = crmLeadsService.getCheckingField();
                break;
            case 2:
                data = crmCustomerService.getCheckingField();
                break;
            case 3:
                data = crmContactsService.getCheckingField();
                break;
            case 4:
                data = crmProductService.getCheckingField();
                break;
            default:
                data = R.error("type不符合要求");
        }
        renderJson(data);
    }
}
